<template>
    <div class="min-h-screen bg-gray-50">
        <!-- 添加/编辑导航模态框 -->
        <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑导航' : '添加导航'" width="500px">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="地址" prop="name">
                    <div style="display: flex;align-items: center;width: 100%;">
                        <el-input style="flex:1" v-model="form.url" placeholder="请输入http或https开头的网址" />
                        <el-button @click="getUrl(form.url)" style="margin-left: 10px">自动获取</el-button>
                    </div>
                </el-form-item>
                <el-form-item label="名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入名称" />
                </el-form-item>
                <el-form-item label="排序" prop="name">
                    <el-input v-model.number="form.sort" placeholder="请输入排序" />
                </el-form-item>
                <el-form-item label="图标" prop="name">
                    <el-upload action="#" :http-request="requestUpload" :show-file-list="false"
                        :before-upload="beforeUpload">
                        <img v-if="imgUrl" :src="imgUrl" alt="" class="form-upload-img">
                        <el-button>
                            {{ imgUrl ? '更改' : '新增' }}
                        </el-button>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">
                        {{ isEdit ? '编辑' : '添加' }}
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <div class="min-h-screen bg-gray-50">
            <div class="container mx-auto max-w-5xl p-6">
                <!-- 基本信息 -->
                <div class="profile-section bg-white rounded-lg shadow-md mb-8 overflow-hidden">
                    <div class="section-header flex justify-between items-center p-4 border-b border-gray-200">
                        <h2 class="section-title text-lg font-semibold text-gray-800 flex items-center gap-2">
                            <i class="fas fa-user text-blue-500"></i> 导航设置
                        </h2>
                    </div>
                    <div class="section-body p-6">
                        <div class="toolbar flex justify-between items-center mb-5">
                            <div class="flex items-center gap-2">
                                <span>导航锁定</span>
                                <el-switch v-model="isLocked" />
                            </div>
                            <div class="flex items-center gap-2">
                                <el-button type="primary" :icon="Plus" @click="openAddModal('custom')">新增网址</el-button>
                                <el-button type="primary" :icon="isSorting ? Check : Switch" @click="toggleSortMode"
                                    :class="{ 'is-sorting': isSorting }">
                                    {{ isSorting ? '完成排序' : '排序' }}
                                </el-button>
                            </div>
                        </div>

                        <div class="navigation-grid pb-5">
                            <!-- 导航卡片 -->
                            <draggable v-model="customNavigations" :disabled="!isSorting || isLocked" item-key="id"
                                class="flex flex-wrap gap-4 w-full" @end="onDragEnd" :animation="150"
                                ghost-class="ghost-card">
                                <template #item="{ element, index }">
                                    <div class="navigation-card border border-gray-200 rounded-lg p-3 relative transition-shadow hover:shadow-md bg-white cursor-pointer"
                                        :class="{ 'cursor-move': isSorting && !isLocked }"
                                        @click="isSorting ? null : openUrl(element.url)">
                                        <div class="flex items-center">
                                            <div class="navigation-icon w-10 h-10 rounded-lg mr-3 overflow-hidden">
                                                <img :src="element.iconUrl" :alt="element.name"
                                                    class="w-full h-full object-contain">
                                            </div>
                                            <div class="navigation-details flex-1">
                                                <div class="navigation-name text-sm font-medium truncate">{{
                                                    element.name }}</div>
                                            </div>
                                        </div>

                                        <div v-if="!isLocked"
                                            class="navigation-actions absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                                            <el-button type="primary" size="small" circle class="!p-1"
                                                @click.stop="editNavigation(element, index)">
                                                <el-icon>
                                                    <Edit />
                                                </el-icon>
                                            </el-button>
                                            <el-button type="danger" size="small" circle class="!p-1"
                                                @click.stop="deleteNavigation(element, index)">
                                                <el-icon>
                                                    <Delete />
                                                </el-icon>
                                            </el-button>
                                        </div>

                                        <div v-if="isSorting && !isLocked"
                                            class="sort-handle absolute top-2 left-2 text-gray-400">
                                            <el-icon>
                                                <Rank />
                                            </el-icon>
                                        </div>
                                    </div>
                                </template>
                            </draggable>
                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { Edit, Delete, Plus, Rank, Switch, Check } from '@element-plus/icons-vue'
import draggable from 'vuedraggable'
import { getNavList, batchSort, deleteNav, addNav, updateNav } from '@/api/user'
import { uploadFile, commonUrlFavicon } from "@/api/file";


const form = ref({
    "siteType": '1',
    "name": "",
    "url": "",
    "logoFileId": "",
    "sort": 0
})

const fileList = ref([]);
const imgUrl = ref(null);

/** 覆盖默认上传行为 */
function requestUpload() {
}

// 解析url
const getUrl = async (url) => {
    const res = await commonUrlFavicon({ url: url });
    imgUrl.value = 'data:image/png;base64,' + res.data.b64;
    form.value.name = res.data.title;
    // 先转为blob
    let blob = dataURLtoBlob('data:image/png;base64,' + res.data.b64);
    // 拿到文件名
    let fileName = form.value.name;
    // 2，在转为 file类型
    fileList.value = blobToFile(blob, fileName);
    uploadImg();
}

//1,先将base64转换为blob
const dataURLtoBlob = (dataurl) => {
    var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
}

//2,再将blob转换为file
const blobToFile = (theBlob, fileName) => {
    theBlob.lastModifiedDate = new Date();  // 文件最后的修改日期
    theBlob.name = fileName;                // 文件名
    return new File([theBlob], fileName, { type: theBlob.type, lastModified: Date.now() });
}


/** 上传预处理 */
const beforeUpload = (file) => {
    if (file.type.indexOf("image/") == -1) {
        proxy.$modal.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
    } else {
        fileList.value = file;
        imgUrl.value = URL.createObjectURL(file);
        uploadImg();
    }
}

/** 上传图片 */
const uploadImg = () => {
    let formData = new FormData();
    formData.append("file", fileList.value);
    uploadFile(formData).then(response => {
        form.value.logoFileId = response.data;
    });
}

// 提交我的导航
const submitForm = () => {
    console.log(form.value)
    if (form.value.id) {
        updateNav(form.value).then(res => {
            if (res.suc) {
                dialogVisible.value = false;
                getNavListFun();
                ElNotification({
                    title: '编辑成功',
                    type: 'success',
                })
            } else {
                ElNotification({
                    title: '编辑失败',
                    type: 'error',
                })
            }
        })
    } else {
        addNav(form.value).then(res => {
            if (res.suc) {
                dialogVisible.value = false;
                getNavListFun();
                ElNotification({
                    title: '提交成功',
                    type: 'success',
                })
            } else {
                ElNotification({
                    title: '提交失败',
                    type: 'error',
                })
            }
        })
    }
}


// 标签页控制
const activeTab = ref('custom')
const isLocked = ref(false)
const isSorting = ref(false)

// 对话框控制
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentEditIndex = ref(-1)

// 导航数据
const customNavigations = ref([])
const leisureNavigations = ref([])

// 获取导航列表
const getNavListFun = async () => {
    try {
        // 这里替换为实际的API调用
        const response = await getNavList();
        console.log(response)
        if (response.suc && response.data) {
            // 假设API返回的数据格式为 { custom: [...], leisure: [...] }
            customNavigations.value = response.data.categories[0].items || [];
            console.log(customNavigations.value)
            // leisureNavigations.value = response.data.data.leisure || []
        }
    } catch (error) {
        console.error('获取导航列表出错:', error)
        ElNotification({
            title: '获取导航列表出错',
            type: 'error',
        })
    }
}

// 批量排序
const batchSortFun = async () => {
    try {
        // 准备排序数据
        console.log(customNavigations.value)
        const sortItems = customNavigations.value.map((item, index) => ({
            navId: item.id,
            sort: index
        }))

        // 调用排序API
        const response = await batchSort({
            items: sortItems
        })

        if (response.suc) {
            ElNotification({
                title: '排序成功',
                type: 'success',
            })
            isSorting.value = false
        } else {
            ElNotification({
                title: '保存排序失败',
                type: 'error',
            })
        }
    } catch (error) {
        console.error('保存排序出错:', error)
        ElNotification({
            title: '保存排序出错',
            type: 'error',
        })
    }
}

// 切换排序模式
const toggleSortMode = () => {
    if (isSorting.value) {
        // 完成排序，调用批量排序接口
        batchSortFun()
    } else {
        // 进入排序模式
        isSorting.value = true
        ElNotification({
            title: '拖动导航项调整顺序，完成后点击"完成排序"',
            type: 'info',
        })
    }
}

// 拖拽结束事件
const onDragEnd = () => {
    // 拖拽结束后的处理，如果需要可以在这里添加逻辑
    console.log('拖拽结束，当前顺序:', customNavigations.value)
}

// 打开添加导航模态框
const openAddModal = (category) => {
    isEdit.value = false;
    reset();
    currentEditIndex.value = -1
    dialogVisible.value = true
}

const reset = () => {
    form.value = {
        "siteType": '1',
        "name": "",
        "url": "",
        "logoFileId": "",
    };
    imgUrl.value = null;
}

// 打开编辑导航模态框
const editNavigation = (item, index) => {
    isEdit.value = true
    currentEditIndex.value = index

    dialogVisible.value = true
    form.value = Object.assign({}, form.value, item);
    form.value.url = item.linkUrl;
    imgUrl.value = item.iconUrl;
}

// 删除导航
const deleteNavigation = async (element, index) => {
    try {
        await ElMessageBox.confirm('确定要删除该导航吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(async () => {
            await deleteNav(element.id).then(res => {
                if (res.suc) {
                    const targetList = activeTab.value === 'custom' ? customNavigations : leisureNavigations
                    targetList.value.splice(index, 1)
                    ElNotification({
                        title: '导航已删除',
                        type: 'success',
                    })
                }
            })
        })

    } catch {
        // 用户取消删除
    }
}

// 打开URL
const openUrl = (url) => {
    if (url) {
        window.open(url, '_blank')
    }
}

// 监听锁定状态变化
const watchLockState = (newValue) => {
    ElNotification({
        title: '导航已锁定',
        type: 'success',
    })
}

// 页面加载时获取导航列表
onMounted(() => {
    getNavListFun()
})
</script>

<style scoped>
.navigation-card {
    position: relative;
}

.navigation-card:hover .navigation-actions {
    opacity: 1;
}

.navigation-icon img {
    width: 100%;
    height: 100%;
    object-fit: contain;
}

.cursor-move {
    cursor: move;
}

.ghost-card {
    opacity: 0.5;
    background: #c8ebfb;
}

.is-sorting {
    background-color: #409eff;
    color: white;
}

/* 响应式调整 */
@media (max-width: 768px) {
    .navigation-grid {
        grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
        gap: 12px;
    }
}
</style>
